﻿@page "/SysTask/Create"
@using Microsoft.AspNetCore.Components
@using SelfService.Model.Models
@using SelfService.ViewModel.SysTaskVMs
@inherits BasePage

<ValidateForm @ref="VForm" Model="@_model" OnValidSubmit="@Submit">
    <Row ItemsPerRow="ItemsPerRow.Two" RowType="RowType.Normal">
        <Select @bind-Value="@_model.Entity.ClassName" 
                Items="_taskList" 
                TValue="string"
                PlaceHolder="@WtmBlazor.Localizer["Sys.PleaseSelect"]" 
                OnValueChanged="ClassNameChanged"></Select>
        <Select @bind-Value="@_model.Entity.TaskType"  PlaceHolder="@WtmBlazor.Localizer["Sys.PleaseSelect"]"></Select>
        <View IsShow="_model.Entity.TaskType is TaskTypeEnum.定时任务">
            <Select @bind-Value="@_model.Entity.TimeType"  PlaceHolder="@WtmBlazor.Localizer["Sys.PleaseSelect"]"></Select>
        </View>
        <View IsShow="_model.Entity.TaskType is TaskTypeEnum.周期任务 or TaskTypeEnum.定时任务">
            <TimePickerBody @bind-Value="@_model.Entity.Interval"/>
        </View>
        <View IsShow="_model.Entity.TaskType is TaskTypeEnum.单次任务">
            <DateTimePicker @bind-Value="@_model.Entity.NextRunTime" ViewMode="DatePickerViewMode.DateTime"/>
        </View>
        <Switch @bind-Value="@_model.Entity.IsEnable"/>
    </Row>
    
    <div class="modal-footer table-modal-footer">
        <Button Color="Color.Warning" Icon="fa fa-close" Text="@WtmBlazor.Localizer["Sys.Close"]" OnClick="OnClose"></Button>
        <Button Color="Color.Primary" ButtonType="ButtonType.Submit" Icon="fa fa-save" Text="@WtmBlazor.Localizer["Sys.Create"]" IsAsync="true"></Button>
    </div>
</ValidateForm>

@code {
    private readonly SysTaskVm _model = new();
    private ValidateForm VForm { get; set; }
    private List<SelectedItem> _taskList = new();
    protected override async Task OnInitializedAsync()
    {
        _taskList = await WtmBlazor.Api.CallItemsApi("/api/SysTask/GetTaskClassList", placeholder: WtmBlazor.Localizer["Sys.PleaseSelect"]);
        await base.OnInitializedAsync();
    }
    
    private async Task Submit(EditContext context)
    {
        await PostsForm(VForm, "/api/SysTask/add", (s) => "Sys.OprationSuccess");
    }

    private Task ClassNameChanged(string value)
    {
        _model.Entity.Name = _taskList.FirstOrDefault(e => e.Value == value)?.Text;
        return Task.CompletedTask;
    }

    public void OnClose()
    {
        CloseDialog();
    }
    
    private Task<bool> OnQueryCondition(string arg)
    {
        return Task.FromResult(_model.Entity.TaskType is TaskTypeEnum.周期任务);
    }
}
